import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:craze/common/index.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_mobx/flutter_mobx.dart';

class QuestionDetailView extends StatefulWidget {
  const QuestionDetailView({super.key});

  @override
  State<QuestionDetailView> createState() => _QuestionDetailViewState();
}

class _QuestionDetailViewState extends State<QuestionDetailView> {
  final QuestionStore _questionStore = getIt<QuestionStore>();
  final UserService _userService = getIt<UserService>();
  final AuthStore _authStore = getIt<AuthStore>();

  final TextEditingController _commentController = TextEditingController();

  // 加载状态
  bool _isLoading = false;

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: 1.sh,
        width: 1.sw,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Observer(
            builder: (_) {
              final question = _questionStore.selectedQuestion;

              if (question == null) {
                return Center(
                  child: Text(
                    'Question not found',
                    style: TextStyle(color: Colors.white, fontSize: 18.sp),
                  ),
                );
              }

              return Stack(
                children: [
                  Column(
                    children: [
                      // 顶部栏：返回按钮和标题
                      _buildAppBar('Online Q&A'),

                      Expanded(
                        child: Stack(
                          children: [
                            Positioned(
                              top: 90.h,
                              left: 0,
                              right: 0,
                              bottom: 0,
                              child: _buildAnswersList(question),
                            ),

                            // 海浪图片
                            Positioned(
                              top: -10.h,
                              left: 10.w,
                              child: Image.asset(
                                MyImages.hailang,
                                width: 170.w,
                                height: 128.h,
                                fit: BoxFit.fill,
                              ),
                            ),
                            _buildQuestionSection(question),
                          ],
                        ),
                      ),
                    ],
                  ),

                  // 悬浮在底部的输入框
                  _buildHuiDaInput(),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  // 构建顶部栏
  Widget _buildAppBar(String title) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => GoRouter.of(context).pop(),
            child: Icon(MyIcons.iconBack, color: Colors.white, size: 20.sp),
          ),
          // 标题
          Expanded(
            child: Center(
              child: Text(
                title,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 22.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQuestionSection(QuestionModel question) {
    return Container(
      width: 1.sw,
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 16.h),
      child: Stack(
        children: [
          // 问题卡片
          Padding(
            padding: EdgeInsets.only(left: 160.w, top: 10.h),
            child: Container(
              height: 76.h,
              padding: EdgeInsets.symmetric(horizontal: 32.w),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.86),
                  colors: [const Color(0xFF0076FF), const Color(0xFF045EC6)],
                ),
                borderRadius: BorderRadius.circular(36.r),
              ),
              child: Center(
                child: Container(
                  constraints: BoxConstraints(maxWidth: 160.w),
                  child: Text(
                    question.content,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建回答列表
  Widget _buildAnswersList(QuestionModel question) {
    final answers = question.answers;

    if (answers.isEmpty) {
      return Center(
        child: Text(
          'No answers yet. Be the first to answer!',
          style: TextStyle(color: Colors.white, fontSize: 14.sp),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.only(left: 20.w, right: 20.w),
      child: Container(
        decoration: BoxDecoration(
          color: MyColors.cardDark,
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
          itemCount: answers.length + 1,
          itemBuilder: (context, index) {
            if (index == answers.length) {
              return SizedBox(height: 80.h);
            }
            return _buildAnswerItem(answers[index]);
          },
        ),
      ),
    );
  }

  // 构建单个回答项
  Widget _buildAnswerItem(AnswerModel answer) {
    final user = _userService.getUserById(answer.userId);
    final userName = user?.name ?? "Unknown";
    final userAvatar = user?.avatar ?? MyImages.touxiang1;

    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息和更多按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  // 头像
                  GestureDetector(
                    onTap: () {
                      GoRouter.of(context).push(
                        AppRouter.otherProfile,
                        extra: {'userId': user?.id},
                      );
                    },
                    child: CircleAvatar(
                      radius: 20.r,
                      backgroundImage: AssetImage(userAvatar),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  // 用户名
                  Text(
                    userName,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                ],
              ),
              // 举报按钮
              GestureDetector(
                onTap: () async {
                  // 举报
                  await ReportDialog.show(
                    context,
                    title: 'Report',
                    description:
                        'Please select a reason for reporting this answer.',
                    onSubmit: (type) async {
                      // block 也算举报成功
                      MyToast.showSuccess(context, 'Report successful');
                      await getIt<QuestionService>().deleteAnswer(
                        _questionStore.selectedQuestion!.id,
                        answer.id,
                      );
                      await _questionStore.loadQuestions();
                      setState(() {});
                    },
                  );
                },
                child: Icon(Icons.more_horiz, color: Colors.white, size: 24.sp),
              ),
            ],
          ),
          SizedBox(height: 12.h),

          // 回答内容
          Text(
            answer.content,
            style: TextStyle(
              color: Colors.white,
              fontSize: 14.sp,
              height: 1.5,
              fontFamily: GoogleFonts.inter().fontFamily,
            ),
          ),
          SizedBox(height: 8.h),

          // 回答时间
          Text(
            _formatDateTime(answer.createdAt),
            style: TextStyle(
              color: Colors.white.withAlpha(153),
              fontSize: 12.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
            ),
          ),
        ],
      ),
    );
  }

  // 构建底部评论输入框
  Widget _buildHuiDaInput() {
    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Container(
        padding: EdgeInsets.only(
          left: 20.w,
          right: 20.w,
          bottom: 30.h,
          top: 10.h,
        ),
        decoration: BoxDecoration(color: Colors.transparent),
        child: Container(
          height: 56.h,
          decoration: BoxDecoration(
            color: Color(0xFF121325),
            borderRadius: BorderRadius.circular(12.r),
            border: Border.all(color: Colors.white, width: 1),
          ),
          child: Row(
            children: [
              // 输入框
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 20.w),
                  child: TextField(
                    controller: _commentController,
                    style: TextStyle(color: Colors.white),
                    decoration: InputDecoration(
                      hintText: 'Leave A Comment',
                      hintStyle: TextStyle(
                        color: Colors.white.withAlpha(153),
                        fontSize: 14.sp,
                      ),
                      border: InputBorder.none,
                    ),
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => _sendAnswer(),
                  ),
                ),
              ),

              // 发送按钮
              Padding(
                padding: EdgeInsets.only(right: 6.w),
                child: GestureDetector(
                  onTap: _isLoading ? null : _sendAnswer,
                  child: Container(
                    width: 75.w,
                    height: 38.h,
                    decoration: BoxDecoration(
                      color: MyColors.blue,
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    child:
                        _isLoading
                            ? SizedBox(
                              width: 20.w,
                              height: 20.h,
                              child: CircularProgressIndicator(
                                strokeWidth: 2.w,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  Colors.white,
                                ),
                              ),
                            )
                            : Center(
                              child: Text(
                                'Send',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 发送回答
  Future<void> _sendAnswer() async {
    // 检查用户是否已登录
    if (_authStore.currentUser == null) {
      // 用户未登录，显示登录提示对话框
      final shouldLogin = await LoginDialog.show(
        context,
        title: 'Login Required',
        description: 'You need to login to leave a comment.',
        returnPath: GoRouterState.of(context).matchedLocation, // 使用当前精确路径
      );

      return; // 不继续执行发送操作
    }

    final content = _commentController.text.trim();
    if (content.isEmpty) return;

    if (_questionStore.selectedQuestion == null ||
        _questionStore.selectedQuestion!.id.isEmpty) {
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 隐藏键盘
      FocusScope.of(context).unfocus();

      await _questionStore.addAnswer(
        _questionStore.selectedQuestion!.id,
        content,
      );
      _commentController.clear();
    } catch (e) {
      // 显示错误提示
      MyToast.showError(context, 'Failed to send answer: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 365) {
      return '${(difference.inDays / 365).floor()} years ago';
    } else if (difference.inDays > 30) {
      return '${(difference.inDays / 30).floor()} months ago';
    } else if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }
}
